$package('upms.role');
upms.role = function(){
	var _box = null;
	var _this = {
		addAction:baseUrl+'/role/add',
		editAction:baseUrl+'/role/edit',
		deleteAction:baseUrl+'/role/delete',
		distributionAction:baseUrl+'/role/distribution',
		distributionDataAction:baseUrl+'/role/distributionDataSave',
		editForm:function(){
			return $("#editForm");
		},
		editWin:function(){
			return $("#edit-win");
		},
		distributionForm:function(){
			return $("#distributionForm");
		},
		distributionWin:function(){
			return $("#distributionWin");
		},
		distributionDataForm:function(){
			return $("#distributionDataForm");
		},
		distributionDataWin:function(){
			return $("#distributionDataWin");
		},
		add:function(){
			if(_this.editForm().form('validate')){
				_this.editForm().attr('action',_this.addAction);
				upms.saveForm(_this.editForm(),function(data){
					var param = $("#searchForm").serializeObject();
					$("#data-list").datagrid('reload',param);
					_this.editWin().dialog('close');
				});
			}
		},
		edit:function(){
			if(_this.editForm().form('validate')){
				_this.editForm().attr('action',_this.editAction);
				upms.saveForm(_this.editForm(),function(data){
					var param = $("#searchForm").serializeObject();
					$("#data-list").datagrid('reload',param);
					_this.editWin().dialog('close');
				});
			}
		},
	    deleteData:function(){
			var rows = $('#data-list').datagrid('getChecked');
			if (upms.checkSelect(rows)){
					$.messager.confirm('Confirm','是否删除选中记录?',function(r){  
						if (r){
					    	var arr = [],idKey = 'roleId'; //主键名称
					    	$.each(rows,function(i,record){
					    		arr.push('roleIds='+record[idKey]);
					    	});
					    	var data = arr.join("&");
					    	upms.deleteForm(_this.deleteAction,data,function(){
								var param = $("#searchForm").serializeObject();
								$("#data-list").datagrid('reload',param);
							});
						}  
				});
			}
		},
		distribution:function(){
			if(_this.distributionForm().form('validate')){
				
				//var nodes =$('#distributionTree').tree('getChecked',['checked','indeterminate']);//保存选中的节点id以及父节点
				var nodes =$('#distributionTree').tree('getChecked',['checked','indeterminate']);
				var cnode='';
				for ( var i = 0; i < nodes.length; i++) {
					if (cnode != '') cnode += ',';
				   cnode += nodes[i].id;
				   }
				$("#distributionForm input[name='menuId']").val(cnode);
				
				_this.distributionForm().attr('action',_this.distributionAction);
				upms.saveForm(_this.distributionForm(),function(data){
					var param = $("#searchForm").serializeObject();
					$("#data-list").datagrid('reload',param);
					_this.distributionWin().dialog('close');
				});
			}
		},
		distributionData:function(){
			var rows = $('#distribution-data-list').datagrid('getChecked');
			if (upms.checkSelect(rows)){
				var roleId = _this.distributionDataForm().find("input[name=roleId]").val();
				//var applicationId=_this.distributionDataForm().find("input[name=applicationId]").val();
		    	var arr = [],idKey = 'dataPermissionId'; //主键名称
		    	arr.push("roleId="+roleId);
		    	//arr.push("applicationId="+applicationId);
		    	$.each(rows,function(i,record){
		    		arr.push('dataPermissionIds='+record[idKey]);
		    	});
		    	var data = arr.join("&");
		    	upms.deleteForm(_this.distributionDataAction,data,function(){
					var param = $("#searchForm").serializeObject();
					$("#data-list").datagrid('reload',param);
					_this.distributionDataWin().dialog('close');
				});
			}
		},
		initForm:function(){
			//新增操作
			$("#addBtn").click(function(){
				$("#editForm").resetForm();
				$("#edit-win").dialog({
					buttons:[
						{
							text:'保  存',
							iconCls: 'icon-ok',
							handler:function(){
								_this.add();
							}
						},
						{
							text:'关  闭',
							iconCls: 'icon-cancel',
							handler:function(){
								_this.editWin().dialog('close');
							}
						}
				]});
				_this.editWin().dialog('open');
			});
			//删除操作
			$("#deleteBtn").click(function(){
				_this.deleteData();
			});
			
			//修改操作
			$("#editBtn").click(function(){
				$("#editForm").resetForm();
				//只能对一条数据编辑
				var rows = $('#data-list').datagrid('getChecked');
				if(rows.length > 1){
					upms.alert('警告','请单选记录后，再进行操作.','warning');
					return false;
				}
				var row = $('#data-list').datagrid('getSelected');
				if (row){
					upms.progress();
					var data ={};
					var idKey = 'roleId'; //主键名称
 					data[idKey] = row.roleId;
					upms.getById(baseUrl+"/role/getById",data,function(result){
						upms.closeProgress();
						$("#editForm").form('load',result);
						$("#edit-win").dialog({
	   						buttons:[
	   							{
	   								text:'保  存',
	   								iconCls: 'icon-ok',
	   								handler:function(){
	   									_this.edit();
	   								}
	   							},
	   							{
	   								text:'关  闭',
	   								iconCls: 'icon-cancel',
	   								handler:function(){
	   									_this.editWin().dialog('close');
	   								}
	   							}
	   					]});
						_this.editWin().dialog('open');
	   				});
				}else{
					upms.alert('警告','未选中记录.','warning');
				}
			});
			//数据权限操作
			$("#distributionDataBtn").click(function(){
				$('#distribution-data-list').datagrid(_this.distributionDataConfig.dataGrid);
				$("#distributionDataForm").resetForm();
				//只能对一条数据编辑
				var rows = $('#data-list').datagrid('getChecked');
				if(rows.length > 1){
					upms.alert('警告','请单选记录后，再进行操作.','warning');
					return false;
				}
				var row = $('#data-list').datagrid('getSelected');
				
				// $("#queryItem").combobox({   onSelect : function(){ } })
				if (row){
					upms.progress();
					var data ={};
					var idKey = 'roleId'; 
 					data[idKey] = row.roleId;
					upms.getById(baseUrl+"/role/getDataById",data,function(result){
						_this.distributionDataForm().form('load',result);
						_this.distributionDataForm().find("input[name=roleId]").val(row.roleId);
					/*	$('#distribution-data-list').datagrid('unselectAll');
						$('#distribution-data-list').datagrid('uncheckAll');*/
						//选择一行
						var rows = $('#distribution-data-list').datagrid('getRows');
						$.each(rows,function(index,row){
							for(var i=0;i<result.length;i++){
								if(row.dataPermissionId==result[i]){
									$('#distribution-data-list').datagrid('checkRow',index);
								}
							}
						})
						$("#distributionDataWin").dialog({
	   						buttons:[
	   							{
	   								text:'保  存',
	   								iconCls: 'icon-ok',
	   								handler:function(){
	   									_this.distributionData();
	   								}
	   							},
	   							{
	   								text:'关  闭',
	   								iconCls: 'icon-cancel',
	   								handler:function(){
	   									_this.distributionDataWin().dialog('close');
	   								}
	   							}
	   					]});
						_this.distributionDataWin().dialog('open');
	   				});
				}else{
					upms.alert('警告','未选中记录.','warning');
				}
			});
			
			//下拉框变动 
			
			 $("#scopeType").combobox({  
				 data:[{'value':'1','text':'全国'},{'value':'2','text':'省'},{'value':'3','text':'市'},{'value':'4','text':'区'},{'value':'5','text':'小区'}],
				 onChange : function(){ 
				  var myOptValue = $("#scopeType").combobox("getValue") ;
				  $("#distribution-data-list").datagrid({
					    url:baseUrl+'/role/getpremissionDataList?applicationId='+applicationId+'&rangeType='+myOptValue,
			   			loadMsg:"处理中，请稍候…",
					    idField:"dataPermissionId",
					    columns:[[
							{field:'dataPermissionId',checkbox:true},
							{field:'dataPermissionName',title:'数据权限',width:'90%',align:'center',sortable:true}
							
						]],
						onLoadSuccess: function(){
							$('#distribution-data-list').datagrid('unselectAll');
							$('#distribution-data-list').datagrid('uncheckAll');
						}});
				//重新加载数据
					/*$.ajax({
						url:baseUrl+'/role/getpremissionDataList?applicationId='+applicationId+'&rangeType='+myOptValue,
						type:"get",
						dataType:"json",
						success:function(data){
							$("#distribution-data-list").datagrid('reload',data);
						}
					});*/
					
				  
			     } 
			 
			 });
			
			//授权操作
			$("#distributionBtn").click(function(){
				$("#distributionForm").resetForm();
				//只能对一条数据编辑
				var rows = $('#data-list').datagrid('getChecked');
				if(rows.length > 1){
					upms.alert('警告','请单选记录后，再进行操作.','warning');
					return false;
				}
				var row = $('#data-list').datagrid('getSelected');
				if (row){
					//upms.progress();
					var data ={};
					var cnode = '';
					var idKey = 'roleId'; //主键名称
 					data[idKey] = row.roleId;
 					
					$("#distributionForm input[name='roleId']").val(row.roleId);
					$("#distributionForm input[name='applicationId']").val(applicationId);
					
					$('#distributionTree').tree({
				          url:baseUrl+'/menu/menuAndOperateTree?applicationId='+applicationId,
				          checkbox:true,
				          onLoadSuccess:function(){
				        	  	//初始化树
								$.ajax({
									url:baseUrl+'/role/getdistributionRoleMenu?roleId='+row.roleId,
									type:"get",
									dataType:"json",
									success:function(data){//直接就是一个数组   遍历树赋值 
										var nodes = $('#distributionTree').tree('getChildren');
										for ( var j = 0; j < data.length;j++) {
											if(data[j].menuType=="operate"){
												var node = $('#distributionTree').tree("find",data[j].menuId);
												if(node && node.target){
													//判断是否选择或者半选状态 
													if($(node.target).find(".tree-checkbox0")[0]){
														$('#distributionTree').tree('check',node.target);
													}
												}
											}
										}
										for ( var j = 0; j < data.length;j++) {
											if(data[j].menuType=="menu"){
												var node = $('#distributionTree').tree("find",data[j].menuId);
												if(node && node.target){
													//判断是否选择或者半选状态 
													if($(node.target).find(".tree-checkbox0")[0]){
														$('#distributionTree').tree('check',node.target);
													}
												}
											}
										}
									}
								});
				          }
				    });

 					$("#distributionWin").dialog({
   						buttons:[
   							{
   								text:'保  存',
   								iconCls: 'icon-ok',
   								handler:function(){
   									_this.distribution();
   								}
   							},
   							{
   								text:'关  闭',
   								iconCls: 'icon-cancel',
   								handler:function(){
   									_this.distributionWin().dialog('close');
   								}
   							}
   					]});
					_this.distributionWin().dialog('open');
				}else{
					upms.alert('警告','未选中记录.','warning');
				}
			});
		},
		
		distributionDataConfig:{
  			dataGrid:{
	   			url:baseUrl+'/role/getpremissionDataList?applicationId='+applicationId+'&rangeType=1',
	   			loadMsg:"处理中，请稍候…",
			    idField:"dataPermissionId",
			    fitColumns:true,
			    columns:[[
					{field:'dataPermissionId',checkbox:true},
					{field:'dataPermissionName',title:'数据权限',width:'90%',align:'center',sortable:true}
					
				]],
				onLoadSuccess: function(){
					$('#distribution-data-list').datagrid('unselectAll');
					$('#distribution-data-list').datagrid('uncheckAll');
				}
			}
		},
		
		config:{
  			dataGrid:{
  				title:'角色列表',
	   			url:'dataList?applicationId='+applicationId,
	   			loadMsg:"处理中，请稍候…",
			    toolbar:"#toolbar",
			    idField:"roleId",
	   			columns:[[
						{field:'roleId',checkbox:true},
						{field:'roleName',title:'角色名称',width:140,align:'center',sortable:true},
						{field:'roleKey',title:'角色KEY',width:140,align:'center',sortable:true},
						{field:'roleDesc',title:'角色描述',width:200,align:'center',sortable:true},
						{field:'createTime',title:'创建时间',width:140,align:'center',sortable:true,formatter:upms.dateTimeFormatter},
						{field:'updateTime',title:'最近登录时间',width:140,align:'center',sortable:true,formatter:upms.dateTimeFormatter}
				]]
			}
		},
		init:function(){
			_this.initForm();
			_box = new MyDataGrid(_this.config); 
			_box.init();
			$('#distribution-data-list').datagrid(_this.distributionDataConfig.dataGrid);
		}
	}
	_this._box = _box;
	return _this;
}();

$(function(){
	upms.role.init();
});		